package dao

import (
	"mldong/internal/modules/sys/entity"
	"mldong/utility"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
)

type RoleMenuDao struct {
}

// 根据角色ID获取菜单ID
func (u *RoleMenuDao) GetMenuIdsByRoleIds(roleIds []string) ([]string, error) {
	values, err := u.Model(nil).Where("role_id", roleIds).Fields("menu_id").Array("menu_id")
	if err != nil {
		return nil, err
	}

	menuIds := make([]string, len(values))
	for i, v := range values {
		menuIds[i] = v.String()
	}
	return menuIds, nil
}

func (u *RoleMenuDao) Insert(entity entity.RoleMenu, tx gdb.TX) (res entity.RoleMenu, _ error) {

	if entity.ID == nil {
		entity.ID = utility.GenId()
	}
	var _, err = u.Model(tx).Data(entity).Insert()
	return entity, err
}

func (u *RoleMenuDao) UpdateById(entity entity.RoleMenu, tx gdb.TX) (count int64, _ error) {

	var result, err = u.Model(tx).Data(entity).Where("id=?", entity.ID).Update()
	count, _ = result.RowsAffected()
	return count, err
}

func (u *RoleMenuDao) DeleteById(id string, tx gdb.TX) (count int64, _ error) {

	var result, err = u.Model(tx).Where("id=?", id).Delete()
	if err != nil {
		return 0, err
	}
	count, _ = result.RowsAffected()
	return count, nil
}

func (u *RoleMenuDao) DeleteByIds(ids []string) (count int64, _ error) {

	var result, err = g.Model("sys_role_menu").WhereIn("id", ids).Delete()
	if err != nil {
		return 0, err
	}
	count, _ = result.RowsAffected()
	return count, nil
}

func (u *RoleMenuDao) GetById(id string) (res entity.RoleMenu, err error) {
	var model = g.Model("sys_role_menu").Where("id=?", id)
	err = model.Scan(&res)
	return res, err
}

func (u *RoleMenuDao) Page(pageNum int, pageSize int, modelHandler func(m *gdb.Model) *gdb.Model) (users []entity.RoleMenu, total int, err error) {
	var model = g.Model("sys_role_menu t")
	// 允许外部修改 model
	if modelHandler != nil {
		model = modelHandler(model)
	}
	err = model.Page(pageNum, pageSize).ScanAndCount(&users, &total, false)
	return users, total, err
}

func (u *RoleMenuDao) List(modelHandler func(m *gdb.Model) *gdb.Model) (list []entity.RoleMenu, err error) {
	var model = g.Model("sys_role_menu t")
	// 允许外部修改 model
	if modelHandler != nil {
		model = modelHandler(model)
	}
	err = model.Scan(&list)
	return list, err
}

func (u *RoleMenuDao) Model(tx gdb.TX) *gdb.Model {
	if tx != nil {
		return tx.Model("sys_role_menu")
	}
	return g.Model("sys_role_menu")
}

func NewRoleMenuDao() *RoleMenuDao {
	return &RoleMenuDao{}
}
